<!-- sign_in -->
<template>
  <div class="container b-container" id="b-container">
    <el-form ref='loginformRef' :model="loginFrom" :rules="loginRules" class="form" id="b-form" method="" action="">
      <h2 class="form_title title">Sign in to BikeWebsite</h2>
      <div class="form__icons">
        <img class="form__icon" src=" ">
        <img class="form__icon" src=" ">
        <img class="form__icon" src=" ">
      </div>
      <span class="form__span">or use your email account</span>
      <el-form-item prop="username" >
        <el-input class="signInput"  type="text" placeholder="用户名" v-model="loginFrom.username"/>
      </el-form-item>
      <el-form-item prop="password" >
        <el-input  class="signInput" type="password" placeholder="密码" v-model.lazy="loginFrom.password"/>
      </el-form-item>
      <a class="form__link">忘记密码?</a>

      <button type="button" class="form__button button submit" @click="sign_in">SIGN IN</button>
    </el-form>
  </div>
</template>

<style>
@import '../assets/Login.css';
</style>

<script setup lang="ts">
import { ref, onMounted,reactive} from 'vue'
import useEmitter from '../hooks/useEmitter.js'
import {ElMessage} from "element-plus";
const emitter = useEmitter();
import router from '../router/index.js'
import store from "../store/index.js";
import axios from 'axios';

onMounted(() => {
  emitter.on('change', (isOpen : boolean) => {
    watch: {
      isOpen:{
        // let aContainer = document.querySelector("#a-container") as any;
        // aContainer.classList.toggle("is-txl");

        //b中样式
        let bContainer = document.querySelector("#b-container") as any;
        bContainer.classList.toggle("is-txl");
        bContainer.classList.toggle("is-z200");
      }
    }
  })
})
/*提交表单步骤，设置响应式变量ref、reactive 设置验证规则，v-model绑定规则 form中设置ref model rules
* 提交表单：？.value.validate((valid)=>{}获取值*/
//登陆注册
const loginFrom = reactive({
  username: "",
  password: ""
})
//登陆注册规则
const loginRules= {
  username:[
      {required:true,message:'请输入账号',trigger:'blur'},
      {min:6,max:10,message: '长度在6到10个字符',trigger:'blur'}
  ],
  password:[
    {required:true,message:'请输入密码',trigger:'blur'},
    {min:6,max:14,message: '长度在6到14个字符',trigger:'blur'}
  ]
}
//ref
const loginformRef=ref(null)
//提交表单
// function sign_in(){
const sign_in=()=>{
  loginformRef.value.validate((valid)=>{
    if(valid){
      //axios传递用户账号密码数据
      let api=store.state.dbApi
      let data={
        username: loginFrom.username,
        password: loginFrom.password
      };
      axios.post(api,data).then(result=>{
        //console.log(Boolean(result.data),result.data)
        if(Boolean(result.data)){
          // 将token本地存储到回话中
          store.commit('setToken',result.data)
          ElMessage.success('登陆成功！')
          /*先import router 才能使用跳转到首页*/
          router.push('/')
        }else{
          ElMessage.error('账号或密码不正确！！')
        }

      }).catch((err)=>{console.log(err)});

    }else {
      return false
    }
  })
}
</script>